package com.yangzc.lion.sys.util.common;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.ServletContext;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.yangzc.lion.sys.util.Commons;


/**
 * SPRING工具实现类
 * 
 * 
 */
public class SpringUtilImpl implements SpringUtil {

	public ApplicationContext getApplicationContext(
			ServletContext servletContext) {
		return WebApplicationContextUtils
				.getWebApplicationContext(servletContext);
	}

	public Object getBean(ServletContext servletContext, String name) {
		return getApplicationContext(servletContext).getBean(name);
	}

	public Object getBean(String name) {
		return getApplicationContext(Commons.ContextUtil.getContext()).getBean(
				name);
	}

	@SuppressWarnings("unchecked")
	public <T> List<T> getBeansForType(Class<T> type) {
		ApplicationContext applicationContext = getApplicationContext(Commons.ContextUtil
				.getContext());
		if (applicationContext == null)
			return null;
		String[] beanNameArr = applicationContext.getBeanNamesForType(type);
		List<String> beanNameList = Arrays.asList(beanNameArr);
		List<T> beanList = new ArrayList<T>();
		for (int i = 0; i < beanNameArr.length; i++) {
			if (beanNameArr[i].endsWith("Target")) {
				String serviceBeanName = beanNameArr[i].substring(0,
						beanNameArr[i].length() - 6) + "Service";
				if (!beanNameList.contains(serviceBeanName))
					beanList.add((T) applicationContext.getBean(beanNameArr[i]));
			} else {
				beanList.add((T) applicationContext.getBean(beanNameArr[i]));
			}
		}
		return beanList;

	}

}
